package com.xuan.juc.single;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.TimeUnit;

public class LazyMan implements Serializable {

    private static boolean flag = false;

    private LazyMan() {
        synchronized (LazyMan.class){

            if (lazyMan!=null){
                throw new RuntimeException("1222");
            }
        }
    }

    private volatile static LazyMan lazyMan;

    // 双重检测锁模式 DCL懒汉式
     public static LazyMan getInstance(){
         if(lazyMan==null){
             synchronized (LazyMan.class){
                 if(lazyMan==null){
                     lazyMan=new LazyMan(); // 不是原子性操作.
                     /*
                     * 1 分配内存空间
                     * 2 执行构造方法 初始化对象
                     * 3 把这个对象指向这个空间
                     * */
                 }
             }
         }

         return lazyMan;
     }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        LazyMan instance = LazyMan.getInstance();

/*        Field flag = LazyMan.class.getField("flag");
        flag.setAccessible(true);
        flag.set(instance,false);*/
        // 用反射破坏实例
        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);// 无视私有构造器

        LazyMan instance2 = declaredConstructor.newInstance();

        System.out.println(instance);
        System.out.println(instance2);

    }
}
